import pickle
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
import torch
class RadioMap:
    def __init__(self, map_value, x_cell_length, y_cell_length):
        self.map = torch.tensor(map_value).double()
        self.x_len = x_cell_length
        self.y_len = y_cell_length
        self.del_value = -2000
    def reshape(self, row_length, col_length):

        # 计算缩放因子
        row_scale = row_length / self.map.shape[0]
        col_scale = col_length / self.map.shape[1]
        x_len = self.x_len / col_scale
        y_len = self.y_len / row_scale
        # 使用zoom进行缩放
        result_map = torch.tensor(zoom(self.map, (row_scale, col_scale), order=3))  # order可以调整平滑程度
        # 更新图像尺寸
        # 创建新的 RadioMap 对象
        return RadioMap(result_map, x_len, y_len)
    def random_sample(self, sample_ratio):
        if not (0 <= sample_ratio <= 1):
            raise ValueError("Sample ratio must be between 0 and 1.")

        total_points = self.map.numel()  # 获取总元素数
        sample_size = int(total_points * sample_ratio)
        sampled_indices = torch.randperm(total_points)[:sample_size]  # 随机选择索引

        sampled_map = torch.full(self.map.shape, self.del_value, dtype=self.map.dtype)  # 创建新张量
        sampled_map.reshape(-1)[sampled_indices] = self.map.reshape(-1)[sampled_indices]  # 赋值

        # 创建新的 RadioMap 对象
        return RadioMap(sampled_map, self.x_len, self.y_len)

    def convert_truth(self):
        self.map = 10 ** (self.map / 10) * 0.001

    def convert_dbw(self):
        self.map = 10 * torch.log10(self.map * 1000)


    def length_get(self, xc, yc):
        cols_f = xc / self.x_len
        rows_f = yc / self.y_len
        cols = int(cols_f)
        rows = int(rows_f)
        # 获取邻居的坐标
        x_indices = [cols - 1, cols, cols + 1]
        y_indices = [rows - 1, rows, rows + 1]
        # 确保索引在有效范围内
        x_indices = [i for i in x_indices if 0 <= i < self.map.shape[1]]
        y_indices = [i for i in y_indices if 0 <= i < self.map.shape[0]]
        # 获取方格的值
        values = [self.map[y, x] for y in y_indices for x in x_indices]
        # 进行加权插值
        if values:
            weights = [1] * len(values)  # 可以根据需要调整权重
            total_weight = sum(weights)
            return sum(v * w for v, w in zip(values, weights)) / total_weight if total_weight > 0 else None
        return None

    def index_get(self, xc, yc):
        return self.map(yc,xc)

def get_matplotlib_axes():
    fig, axes = plt.subplots(1, 1, figsize=(9, 8), sharex=True, sharey=True)
    fig.subplots_adjust(
        top=0.9,
        bottom=0.1,
        left=0.1,
        right=0.9,
        hspace=0.2,
        wspace=0.2,
    )
    return axes


if __name__ == '__main__':
    with open('data.pkl', 'rb') as file:
        x, y, field_temp, field_temp_grid = pickle.load(file)
    plt.rcParams["image.origin"] = "lower"
    plt.rcParams["image.cmap"] = "jet"
    plt.rcParams["image.interpolation"] = "gaussian"
    axes = get_matplotlib_axes()

    field_temp_reshaped = field_temp.reshape((366, 278)).transpose()
    # # 计算差
    # difference = field_temp_reshaped - field_temp_grid
    # # 计算 2 范数
    # l2_norm = np.linalg.norm(difference)
    radio_map_value = field_temp_reshaped
    x_reso_dis = 5  # km
    y_reso_dis = 5  # km
    a = 1
    b = 2
    a = 1
    b = 2
    a = 1
    b = 2   
    b = 2
    a = 1
    b = 2
    b = 2
    radiomap1  = RadioMap(radio_map_value,x_reso_dis,y_reso_dis)
    rand_sample_img = radiomap1.random_sample(0.05)

print("hello world")

